<template>
  <!-- 测量数据取样配置表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="props.isReadonly ? '1000px' : '500px'"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      v-show="!props.isReadonly"
      :model="formData"
      :rules="rules"
      label-width="180"
    >
      <el-row>
        <el-col :span="22">
          <el-form-item label="取样规则编码" prop="countRuleCode">
            <el-input
              v-model="formData.countRuleCode"
              placeholder="请输入取样规则编码"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="过程监控分类" prop="abilityType">
            <el-select
              v-model="formData.abilityType"
              placeholder="请选择过程监控分类"
              clearable
              :disabled="!!abilityType"
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore
                  .filterDictList('AbilityType')
                  ?.filter((item) => !['0', '1'].includes(item.value))"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="计算样本最低数量" prop="ruleLowestNum">
            <el-input
              v-model="formData.ruleLowestNum"
              placeholder="请输入计算样本最低数量"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-popover
            placement="top-end"
            :width="200"
            trigger="hover"
            content="趋势图能够开始计算的最小采样数"
          >
            <template #reference>
              <span class="yellow-icon">
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </template>
          </el-popover>
        </el-col>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item
              label="计算最低取样时长(天)"
              prop="ruleLowestDuration"
            >
              <el-input
                v-model="formData.ruleLowestDuration"
                placeholder="请输入计算最低取样时长(天)"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="趋势图能够开始计算的最小采样时间"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row style="width: 100%">
          <el-col :span="22">
            <el-form-item
              :label="!isNotStage ? '去掉数量' : '样本节拍比对件数'"
              prop="continuousNum"
            >
              <el-input
                v-model="formData.continuousNum"
                :placeholder="`请输入${
                  !isNotStage ? '去掉数量' : '样本节拍比对件数'
                }`"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              :content="`${
                !isNotStage
                  ? '每次执行完事去掉检测数量'
                  : '趋势图每次采样采集数据，之前必须是连续个数'
              }`"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="节拍比对倍数" prop="intervalSecond">
              <el-input
                v-model="formData.intervalSecond"
                placeholder="请输入节拍比对倍数"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="趋势图采样数量之间时间间隔小于，则合格采样"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-col :span="22">
          <el-form-item label="首次执行时间" prop="firstExecutionTime">
            <el-date-picker
              style="width: 100%"
              v-model="formData.firstExecutionTime"
              :disabled="formData.id != ''"
              type="datetime"
              placeholder="请选择首次执行时间"
              format="YYYY-MM-DD HH"
              value-format="YYYY-MM-DD HH"
            />
          </el-form-item>
        </el-col>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="取样间隔（小时）" prop="intervalHour">
              <el-input
                v-model="formData.intervalHour"
                placeholder="请输入取样间隔（小时）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="进行采样的间隔时间"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="CPK计算周期（小时）" prop="cpkComputeHour">
              <el-input
                v-model="formData.cpkComputeHour"
                placeholder="请输入CPK计算周期（小时）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="趋势图首次计算后，进行CPK计算的间隔时间"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="取样最大范围" prop="maxRange">
              <el-input
                v-model="formData.maxRange"
                placeholder="请输入取样最大范围"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="趋势图计算采样数最大范围（按月或按采样数量）"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="取样范围滚动间隔" prop="rollInterval">
              <el-input
                v-model="formData.rollInterval"
                placeholder="请输入取样范围滚动间隔"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="达到最大范围后，舍弃最早数据"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
        <el-row v-if="isNotStage" style="width: 100%">
          <el-col :span="22">
            <el-form-item label="取样最大范围单位" prop="maxUnit">
              <el-select
                v-model="formData.maxUnit"
                placeholder="请选择取样最大范围单位"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('MaxUnit')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-popover
              placement="top-end"
              :width="200"
              trigger="hover"
              content="取样最大范围的单位（月/采样个数）"
            >
              <template #reference>
                <span class="yellow-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
      </el-row>
    </el-form>

    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">取样规则编码</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.countRuleCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">过程监控分类</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ useDictionary("AbilityType", formData.abilityType) || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计算样本最低数量</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.ruleLowestNum || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">计算最低取样时长(天)</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.ruleLowestDuration || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">样本节拍比对件数</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.continuousNum || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">节拍比对倍数</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.intervalSecond || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">首次执行时间</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.firstExecutionTime || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">取样间隔（小时）</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.intervalHour || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">CPK计算周期（小时）</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.cpkComputeHour || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">取样最大范围</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.maxRange || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">取样范围滚动间隔</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.rollInterval || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="isNotStage">
        <template #label>
          <div class="cell-item">取样最大范围单位</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ useDictionary("MaxUnit", formData.maxUnit) || "" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly && formData.programId && formData.id"
          type="danger"
          :loading="loading"
          @click="deleteItem(formData.id)"
          >删 除
        </el-button>
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { QuestionFilled } from "@element-plus/icons-vue";
import { useDictionary } from "../../../../utils/useTable";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPCMCONFIGMEASUREMENTSADDORUPDATEPLD",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  abilityType: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const isNotStage = ref(true);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  countRuleCode: [
    { required: true, message: "请输入取样规则编码", trigger: "change" },
    { max: 20, message: "规则编码不能超过20个字符", trigger: "blur" },
  ],
  abilityType: [
    { required: true, message: "请选择过程监控分类", trigger: "change" },
  ],
  ruleLowestNum: [
    { required: true, message: "请输入计算样本最低数量", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  ruleLowestDuration: [
    {
      required: true,
      message: "请输入计算最低取样时长(天)",
      trigger: "change",
    },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  continuousNum: [
    { required: true, message: "请输入数量", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  intervalSecond: [
    { required: true, message: "请输入节拍比对倍数", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  firstExecutionTime: [
    { required: true, message: "请选择首次执行时间", trigger: "change" },
  ],
  intervalHour: [
    { required: true, message: "请输入取样间隔（小时）", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  cpkComputeHour: [
    { required: true, message: "请输入CPK计算周期（小时）", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  maxRange: [
    { required: true, message: "请输入取样最大范围", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  rollInterval: [
    { required: true, message: "请输入取样范围滚动间隔", trigger: "change" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  maxUnit: [
    { required: true, message: "请选择取样最大范围单位", trigger: "change" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  countRuleCode: "",
  programId: "",
  abilityType: "",
  ruleLowestNum: "",
  ruleLowestDuration: "",
  continuousNum: "",
  intervalSecond: "",
  firstExecutionTime: "",
  intervalHour: "",
  cpkComputeHour: "",
  maxRange: "",
  rollInterval: "",
  maxUnit: "",
  version: "",
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    // if (newVal?.id) {
    const {
      id,
      countRuleCode,
      programId,
      abilityType,
      ruleLowestNum,
      ruleLowestDuration,
      continuousNum,
      intervalSecond,
      intervalHour,
      firstExecutionTime,
      cpkComputeHour,
      maxRange,
      rollInterval,
      maxUnit,
      version,
      enabled,
      deleted,
      createTime,
      createdUserId,
      createdUserName,
      lastUpdatedUserId,
      lastUpdatedUserName,
      lastUpdateTime,
    } = newVal;
    Object.assign(formData, {
      id,
      countRuleCode,
      programId,
      abilityType,
      ruleLowestNum,
      ruleLowestDuration,
      continuousNum,
      intervalSecond,
      intervalHour,
      firstExecutionTime,
      cpkComputeHour,
      maxRange,
      rollInterval,
      maxUnit: maxUnit ?? undefined,
      version,
      enabled,
      deleted,
      createTime,
      createdUserId,
      createdUserName,
      lastUpdatedUserId,
      lastUpdatedUserName,
      lastUpdateTime,
    });
    formData.abilityType = JSON.stringify(formData.abilityType);
    formData.maxUnit = JSON.stringify(formData.maxUnit);
    // }
    if (newVal?.abilityType) {
      formData.abilityType = newVal.abilityType.toString();
    }
    if (newVal?.programId) {
      formData.programId = newVal.programId;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.countRuleCode = "";
  formData.programId = "";
  formData.abilityType = "";
  formData.ruleLowestNum = "";
  formData.ruleLowestDuration = "";
  formData.continuousNum = "";
  formData.intervalSecond = "";
  formData.intervalHour = "";
  formData.firstExecutionTime = "";
  formData.cpkComputeHour = "";
  formData.maxRange = "";
  formData.rollInterval = "";
  formData.maxUnit = "";
  formData.version = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
}

const loading = ref(false);

/** 测量数据取样配置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      if (formData.abilityType === "3") {
        formData.ruleLowestDuration = "";
        formData.intervalSecond = "";
        formData.intervalHour = "";
        formData.cpkComputeHour = "";
        formData.maxRange = "";
        formData.rollInterval = "";
        formData.maxUnit = "";
      }
      await request({
        url: "/dmpDosPcm/pcmconfigmeasurements/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

watch(
  () => formData.abilityType,
  (newVal) => {
    isNotStage.value = newVal !== "3";
  },
  { deep: true }
);

const deleteItem = (id) => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/dmpDosPcm/pcmconfigmeasurements/deleteItem/${id}`,
      method: "post",
    }).then(() => {
      ElMessage.success("删除成功");
      closeDialog();
    });
  });
};
</script>
<style scoped>
.yellow-icon :deep(.el-icon) {
  /* color: #ffb441; */
  color: gray;
  font-size: 15px; /* 根据需要调整大小 */
  height: 65%;
  margin-left: 5px;
}

::v-deep .is-bordered-label {
  width: 25% !important;
}

::v-deep .is-bordered-content {
  width: 25% !important;
}

.el-picker-panel {
  .el-scrollbar:nth-of-type(2) {
    display: none !important;
  }
}

.el-time-spinner {
  text-align: center;
}
</style>
